package com.tomas.demo.controller.upload;

import com.alibaba.fastjson.JSON;
import com.github.tobato.fastdfs.FdfsClientConfig;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.github.tobato.fastdfs.service.GenerateStorageClient;
import com.tomas.demo.common.jsonResult.ApiResult;
import com.tomas.demo.common.utils.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Tomas
 * @date 16/5/24 下午6:50
 * @what
 */
@Slf4j
@Controller
@RequestMapping(value = "/ajax")
@Import(FdfsClientConfig.class)
public class AjaxUploadController {



    @Value("${deafult.upload.folder}")
    private  String directory;

    @Value("${deafult.images.host}")
    private  String IMAGEHOST;

    /**
     * 跳转H5 ajax上传 H5
     * @return
     */
    @RequestMapping(value = "/h5")
    public String toAjaxUploadH5(){
        return  "/upload/H5ajaxUpload";
    }


    /**
     * 跳转H5 ajax上传 方式一
     * @return
     */
    @RequestMapping(value = "/1")
    public String toAjaxUpload1(){
        return  "/upload/ajaxUploader1";
    }
    /**
     * 跳转H5 ajax上传 方式二
     * @return
     */
    @RequestMapping(value = "/2")
    public String toAjaxUpload2(){
        return  "/upload/ajaxUploader2";
    }

    /**
     * 跳转H5 ajax上传 方式三
     * @return
     */
    @RequestMapping(value = "/3")
    public String toAjaxUpload3(){
        return  "/upload/ajaxUploader3";
    }


    /**
     * 跳转 兼容mobile的上传
     * @return
     */
    @RequestMapping(value = "/mobile")
    public String mobileAjaxUpload(){
        return  "/upload/mobileUploader";
    }

    /**
     * 跳转 iframe上传
     * @return
     */
    @RequestMapping(value = "/iframe")
    public String iframeAjaxUpload(){
        return  "/upload/iframeUploader";
    }


    /**
     * 跳转 百度编辑器的上传
     * @return
     */
    @RequestMapping(value = "/baidu")
    public String baiduAjaxUpload(){
        return  "/upload/webUploader";
    }

    /**
     * 跳转 腾讯UI的上传
     * @return
     */
    @RequestMapping(value ="/tencent")
    public String tencetnAjaxUpload(){
        return  "/upload/tencentUploader";
    }
    @Autowired
    FastFileStorageClient fastFileStorageClient;

    @Autowired
    GenerateStorageClient defaultGenerateStorageClient;

    /**
     * POST /uploadFile -> receive and locally save a file.
     *                     方式一: 接收文件并保存为本地文件
     * @param uploadfile
     * @return
     */
    @RequestMapping(value = "/local/upload", method = RequestMethod.POST)
    @ResponseBody
    public ApiResult uploadFile(
            @RequestParam("uploadfile") MultipartFile uploadfile) {

        try {
            // Get the filename and build the local file path (be sure that the
            // application have write permissions on such directory)
            String filename = uploadfile.getOriginalFilename();

            // directory = "/opt/data/uploads";
            String filepath = Paths.get(directory, filename).toString();

            // Save the file locally
            BufferedOutputStream stream =new BufferedOutputStream(new FileOutputStream(new File(filepath)));
            stream.write(uploadfile.getBytes());
            stream.close();
            log.info("上传完成 保存路径{}", filepath);
            return  ApiResult.ok("ok", filepath);
        }
        catch (Exception e) {
            log.error(e.getMessage());
            return new ApiResult("500","服务器上传出错");
        }
    }

    @RequestMapping(value ="/upload")
     @ResponseBody
     public ApiResult dfsUpload(@RequestParam("uploadfile") MultipartFile uploadfile) {
        try {
            //方式一:
            //默认group1   inputStream 文件流 ,long 文件大小 , String 文件后缀 , Set<MateData> 附加信息
            // StorePath storePath = fastFileStorageClient.uploadFile(uploadfile.getInputStream(), uploadfile.getSize(), FileUtils.getFileExt(uploadfile.getOriginalFilename()), null);
            //log.info(IMAGEHOST + storePath.getGroup() + "/" + storePath.getPath());
            //return ApiResult.ok("ok",IMAGEHOST+txt.getGroup()+"/"+txt.getPath());

            //方式二:
            //group 默认group1, inputStream 文件流 ,long 文件大小 , String 文件后缀
            StorePath txt = defaultGenerateStorageClient.uploadFile(null, uploadfile.getInputStream(), uploadfile.getSize(), FileUtils.getFileExt(uploadfile.getOriginalFilename()));
            log.info("上传完成 保存路径{}", IMAGEHOST+txt.getGroup()+"/"+txt.getPath());
            return ApiResult.ok("上传成功!",IMAGEHOST+txt.getGroup()+"/"+txt.getPath());
        }catch (Exception e){
            log.error(e.getMessage());
            return new ApiResult("500","上传失败! 服务器上传出错");
        }
    }
    @RequestMapping(value ="/iframe/upload", produces = "text/html")
    public void dfsUpload(@RequestParam("uploadfile") MultipartFile uploadfile,HttpServletResponse response) {
        try {
            //group 默认group1, inputStream 文件流 ,long 文件大小 , String 文件后缀
            StorePath txt = defaultGenerateStorageClient.uploadFile(null, uploadfile.getInputStream(), uploadfile.getSize(), FileUtils.getFileExt(uploadfile.getOriginalFilename()));
            log.info("上传完成 保存路径{}", IMAGEHOST+txt.getGroup()+"/"+txt.getPath());
            response.getWriter().write(JSON.toJSONString(ApiResult.ok("ok", IMAGEHOST + txt.getGroup() + "/" + txt.getPath())));
            //response. ApiResult.ok("ok", IMAGEHOST + txt.getGroup() + "/" + txt.getPath());
        }catch (Exception e){
            log.error(e.getMessage());
            try {
                response.getWriter().write(JSON.toJSONString(new ApiResult("400","请求参数有误")));
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            // return new ApiResult("400","请求参数有误");
        }
    }


    @RequestMapping(value ="/multiUpload")
    @ResponseBody
    public ApiResult multiUpload(@RequestParam("uploadfiles") MultipartFile[] uploadfiles) {
        if (null!=uploadfiles && uploadfiles.length>0){
            try {
                List<String> imglist=new ArrayList<>();
                for (MultipartFile uploadfile:uploadfiles) {
                    StorePath txt = defaultGenerateStorageClient.uploadFile(null, uploadfile.getInputStream(), uploadfile.getSize(), FileUtils.getFileExt(uploadfile.getOriginalFilename()));
                    log.info("上传完成 保存路径{}", IMAGEHOST+txt.getGroup()+"/"+txt.getPath());
                    imglist.add(IMAGEHOST+txt.getGroup()+"/"+txt.getPath());
                }
                return ApiResult.ok("ok",imglist);
                //return ApiResult.ok("ok",IMAGEHOST+txt.getGroup()+"/"+txt.getPath());
            }catch (Exception e){
                log.error(e.getMessage());
                return new ApiResult("500","上传失败! 服务器上传出错");
            }
        }else {
            return new ApiResult("400","请求参数有误");
        }

    }

    @RequestMapping(value ="/base64")
    @ResponseBody
    public ApiResult base64(@RequestParam("base64") String uploadfile) {
        String postfix="jpg";
        if(!StringUtils.isEmpty(uploadfile)){
            if(uploadfile.startsWith("data:image/")){
                postfix = uploadfile.split(";")[0].substring(11);
            }
        }
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] bytes1 = decoder.decodeBuffer(uploadfile);
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
            StorePath txt = defaultGenerateStorageClient.uploadFile(null, bais,bytes1.length, postfix);
            /// return ApiResult.ok("ok",imglist);
            return ApiResult.ok("ok",IMAGEHOST+txt.getGroup()+"/"+txt.getPath());
        }catch (Exception e){
            log.error(e.getMessage());
            return new ApiResult("500","上传失败! 服务器上传出错");
        }
       /* if (null!=uploadfiles && uploadfiles.length>0){
            try {
                List<String> imglist=new ArrayList<>();
                for (MultipartFile uploadfile:uploadfiles) {
                    StorePath txt = defaultGenerateStorageClient.uploadFile(null, uploadfile.getInputStream(), uploadfile.getSize(), FileUtils.getFileExt(uploadfile.getOriginalFilename()));
                    log.info("上传完成 保存路径{}", IMAGEHOST+txt.getGroup()+"/"+txt.getPath());
                    imglist.add(IMAGEHOST+txt.getGroup()+"/"+txt.getPath());
                }
                return ApiResult.ok("ok",imglist);
                //return ApiResult.ok("ok",IMAGEHOST+txt.getGroup()+"/"+txt.getPath());
            }catch (Exception e){
                log.error(e.getMessage());
                return new ApiResult("400","请求参数有误");
            }
        }else {
            return new ApiResult("400","请求参数有误");
        }*/
        //return ApiResult.ok("ok",uploadfile);
    }


}
